//
//  SSSExchangeController.m
//  SSSAllRollAgency
//
//  Created by Darker on 2017/3/13.
//  Copyright © 2017年 Darker. All rights reserved.
//

#import "SSSExchangeController.h"
#import "exchangeCell.h"
#import "SSSexchangeDetailController.h"
#import "ExchangeRecordModel.h"

@interface SSSExchangeController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIImageView *_headerView;//头部视图
    UITableView *_listTableView;//列表展示
    NSMutableArray *_dataArray;//数据源数组
    NSInteger _currentPage;
    UILabel *moneyLabel;
}
/** 请求参数 */
@property(nonatomic, strong) NSMutableDictionary *parameter;

@end

static NSString * const exchangeID = @"exchangeCell";

@implementation SSSExchangeController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.title = @"兑换记录";
    self.view.backgroundColor = [UIColor colorWithHex:@"F9F9FA"];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];

    //加载头视图
    [self addHeaderView];
    
    //初始化tableView
    [self initListTableView];
    
    [self reloadHeaderData];
    [self refreshLoad];
}
#pragma mark - 加载头部视图
- (void)addHeaderView{
    
    _headerView = [[UIImageView alloc]init];
    _headerView.image = [UIImage imageNamed:@"img_bg@2x"];
    _headerView.sd_layout
    .topSpaceToView(self.view,64)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .heightIs(HeigthIos6CompeteWithCurrent(120));
    
    UILabel *moneyTextLabel = [[UILabel alloc]init];
    moneyTextLabel.textColor = [UIColor whiteColor];
    moneyTextLabel.textAlignment = NSTextAlignmentCenter;
    moneyTextLabel.font = [SSSFont systemFontOfSize:15];
    moneyTextLabel.text = @"累计兑换金额";
    [_headerView addSubview:moneyTextLabel];
    moneyTextLabel.sd_layout
    .centerXEqualToView(_headerView)
    .topSpaceToView(_headerView,HeigthIos6CompeteWithCurrent(30))
    .heightIs(HeigthIos6CompeteWithCurrent(20))
    .widthIs(WidthIos6CompeteWithCurrent(300));
    
    //中间横线
    UIImageView *lineView = [[UIImageView alloc]init];
    lineView.image = [UIImage imageNamed:@""];
   // lineView.backgroundColor = [UIColor redColor];
    [_headerView addSubview:lineView];
    lineView.sd_layout
    .centerXEqualToView(_headerView)
    .topSpaceToView(moneyTextLabel,HeigthIos6CompeteWithCurrent(10))
    .widthIs(WidthIos6CompeteWithCurrent(60))
    .heightIs(HeigthIos6CompeteWithCurrent(1));
    
    //金额
    moneyLabel = [[UILabel alloc]init];
    moneyLabel.textAlignment = NSTextAlignmentCenter;
    [_headerView addSubview:moneyLabel];
    moneyLabel.text = @"8000000.0";
    moneyLabel.font = [SSSFont systemFontOfSize:20];
    moneyLabel.textColor = [UIColor whiteColor];
    moneyLabel.sd_layout
    .centerXEqualToView(_headerView)
    .topSpaceToView(lineView,HeigthIos6CompeteWithCurrent(10))
    .heightIs(HeigthIos6CompeteWithCurrent(30))
    .widthIs(WidthIos6CompeteWithCurrent(300));
}
#pragma mark - 初始化tableView
- (void)initListTableView{
    
    _listTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, FSCREEN_Width, FSCREEN_Height) style:UITableViewStylePlain];
    _listTableView.backgroundColor = [UIColor clearColor];
    _listTableView.delegate = self;
    _listTableView.dataSource = self;
    _listTableView.rowHeight = HeigthIos6CompeteWithCurrent(150);
    _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _listTableView.tableHeaderView = _headerView;
    [self.view addSubview:_listTableView];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Class currentClass = [exchangeCell class];
    
    exchangeCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(currentClass)];
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (!cell) {
        cell = [[exchangeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:exchangeID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = _dataArray[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ExchangeRecordModel *model = _dataArray[indexPath.row];
    SSSexchangeDetailController *exchangeDetailVc = [[SSSexchangeDetailController alloc]init];
    exchangeDetailVc.idStr = [NSString stringWithFormat:@"%ld",model.ID];
    [self.navigationController pushViewController:exchangeDetailVc animated:YES];
    
}
- (void)refreshLoad{
    
    ZDRefreshHeader *header = [ZDRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 马上进入刷新状态
    [header beginRefreshing];
    // 设置header
    _listTableView.mj_header = header;
    
    // 上拉加载
    _listTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    
}

- (void)loadNewData{
    
    [_listTableView.mj_footer endRefreshing];
    _currentPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"currentPage"] = @(_currentPage);
    params[@"pageSize"] = @"5";
    self.parameter = params;

    [[XHRequestManager manager] getRequest:kConfigPath(kExchangeRecrod) params:params success:^(id  _Nonnull responseObj) {
        
        XHLog(@"-----%@",responseObj);
        
        if ([responseObj[@"status"] intValue] == 0){
            
            [_dataArray removeAllObjects];
            
            if ([responseObj[@"data"][@"pageList"] count] == 0) {
                
                showTipHudStr(@"还没有兑换记录");
                [_listTableView.mj_header endRefreshing];
                _listTableView.mj_footer.hidden = YES;
                
            }else{
                
                NSArray *array = [NSArray modelArrayWithClass:[ExchangeRecordModel class] json:responseObj[@"data"][@"pageList"]];
                
                _dataArray = [NSMutableArray array];
                [_dataArray addObjectsFromArray:array];
                
                //不是最后一次请求
                if (self.parameter != params) return ;
                //回到主线程刷新表格
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //刷新表格
                    [_listTableView reloadData];
                    
                });
                
                [_listTableView.mj_header endRefreshing];
                
                // _listTableView.mj_footer.hidden = (_currentPage == 1);
                
                if ([responseObj[@"data"][@"hasNextPage"] intValue] == 0) {
                    
                    [_listTableView.mj_footer endRefreshingWithNoMoreData];
                    
                }else{
                    [QMUITips showError:responseObj[@"message"] inView:self.view hideAfterDelay:2];
                    [_listTableView.mj_header endRefreshing];
                }

            }
            
            
        }else{
            
            [QMUITips showError:responseObj[@"message"] inView:self.view hideAfterDelay:2];
            [_listTableView.mj_header endRefreshing];
        }

        
    } failure:^(NSError * _Nonnull error) {
        
        XHLog(@"---error----%@",error.localizedDescription);
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
        [_listTableView.mj_header endRefreshing];
    }];
    
}
- (void)loadMoreData{
    
    [_listTableView.mj_header endRefreshing];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"currentPage"] = @(++_currentPage);
    params[@"pageSize"] = @"5";
    self.parameter = params;
    
    [[XHRequestManager manager] getRequest:kConfigPath(kExchangeRecrod) params:params success:^(id  _Nonnull responseObj) {
        
        XHLog(@"-----%@",responseObj);
        
        if ([responseObj[@"status"] intValue] == 0){
            
            NSArray *array = [NSArray modelArrayWithClass:[ExchangeRecordModel class] json:responseObj[@"data"][@"pageList"]];
            
            [_dataArray addObjectsFromArray:array];
            //不是最后一次请求
            if (self.parameter != params) return ;
            //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //刷新表格
                [_listTableView reloadData];
                
            });
            
            [_listTableView.mj_header endRefreshing];
            
            // _listTableView.mj_footer.hidden = (_currentPage == 1);
            
            if ([responseObj[@"data"][@"hasNextPage"] intValue] == 0) {
                
                [_listTableView.mj_footer endRefreshingWithNoMoreData];
                
            }else{
                
                //[QMUITips showError:responseObj[@"message"] inView:self.view hideAfterDelay:2];
                [_listTableView.mj_footer endRefreshing];
            }
            
        }else{
            
            [QMUITips showError:responseObj[@"message"] inView:self.view hideAfterDelay:2];
            [_listTableView.mj_footer endRefreshing];
        }

        
    } failure:^(NSError * _Nonnull error) {
        
        XHLog(@"---error----%@",error.localizedDescription);
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
        [_listTableView.mj_footer endRefreshing];
    }];
    
}


- (void)reloadHeaderData{

    [[XHRequestManager manager] getRequest:kConfigPath(kTotal) params:nil success:^(id  _Nonnull responseObj) {
        
        if ([responseObj[@"ststus"] intValue] == 0) {
            
            //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //刷新表格
                moneyLabel.text = [NSString stringWithFormat:@"%@",responseObj[@"data"][@"total"]];
                
            });
            
        }else{
            
            [QMUITips showError:responseObj[@"message"] inView:self.view hideAfterDelay:2];
        }

    } failure:^(NSError * _Nonnull error) {
        
         [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
    }];
    
}

@end
